package com.lcf.user.kafka;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyProducer {

    private static Logger logger = LoggerFactory.getLogger(MyProducer.class);

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @GetMapping("/kafka/test1")
    public String test1() {
        ListenableFuture send = kafkaTemplate.send("first-topic", "aaaa");

        return "success";
    }
    @GetMapping("/kafka/image/{msg}")
    public String imageTest1(@PathVariable String msg) {
        ListenableFuture send = kafkaTemplate.send("image-topic", msg);

        return "success";
    }
    @GetMapping("/kafka/test2")
    public String test2(){
        try {
            ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("first-topic","luoye", "hello kafka");
            future.addCallback(new ListenableFutureCallback<SendResult< String, String >>() {
                @Override
                public void onSuccess(SendResult<String, String> result) {
                    System.out.println(result.toString());
                    System.out.println("推送消息成功");
                }

                @Override
                public void onFailure(Throwable throwable) {
                    System.out.println("推送消息失败");
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }
}
